#include "stdafx.h"


#include "qmemfile.h"  
using namespace micro::files;


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

void QMemFile::Grow(size_t nGrowTo)
{
	if (m_nBufSize < (UINT)nGrowTo)
	{
		if (m_nGrowBy == 0)
			throw QError();

		size_t nNewSize = m_nBufSize;
		while (nNewSize < nGrowTo)
			nNewSize += m_nGrowBy;
		BYTE* lpNew;
		if (m_lpBuf)
			lpNew = (BYTE*)realloc((void*) m_lpBuf, nNewSize);
		else
			lpNew = (BYTE*)malloc(nNewSize);

		if (!lpNew)
				throw QError();

		m_nBufSize = nNewSize;
		m_lpBuf = lpNew;
	}
} 

void QMemFile::SetFileSize(ULONGLONG nNewLen)
{
	if (m_nBufSize < (size_t)nNewLen)
		Grow((size_t)nNewLen);
	else
		m_nPos = (size_t)nNewLen;
	m_nDataSize = (size_t)nNewLen;
}

size_t QMemFile::Read(void *lpBuf, size_t  nCount)
{
	if (m_nPos >= m_nDataSize)
		return 0;
	size_t  nToRead = (m_nPos + nCount > m_nDataSize) ? (DWORD)m_nDataSize - m_nPos : nCount;
	memcpy(lpBuf, m_lpBuf + m_nPos, nToRead);
	m_nPos += nToRead;
	return nToRead;

}

size_t QMemFile::Write(const void *lpBuf, size_t nCount)
{
	if (!nCount)
		return 0;

	if (m_nPos + nCount > m_nBufSize)
		Grow(m_nPos + nCount);
	memcpy(m_lpBuf + m_nPos, lpBuf, nCount);
	m_nPos += nCount;
	if (m_nPos > m_nDataSize)
		m_nDataSize = m_nPos;

	return nCount;
}
ULONGLONG QMemFile::Seek(LONGLONG lOff, DWORD nFrom)
{
	ULONGLONG lNew = m_nPos;

	if (nFrom == begin)
	{
		if (lOff < 0)
				throw QError();
		lNew = lOff;
	}
	else if (nFrom == current)
	{
		if (lOff < 0 && (ULONGLONG)(-lOff) > lNew)
				throw QError();
		lNew += lOff;
	}
	else if (nFrom ==  end)
	{
		if (lOff < 0 && ULONGLONG(-lOff) > m_nDataSize)
				throw QError();
		lNew = m_nDataSize + lOff;
	}
	else
		return lNew;

	// assumption that size_t is always signed
	if (lNew > (size_t)(-1)) // max of size_t
			throw QError();
	if (lNew > m_nDataSize)
		Grow((size_t)lNew);
	
	m_nPos = (size_t)lNew;
	return lNew;
}
